<?php
/**
 * Created by Phpstorm
 * User: 一个猫
 * Date: 2023/11/24
 * Time: 11:08
 */

namespace App\Server;

use App\Jobs\CardCreateJob;
use App\Models\Brand as BrandModel;

class CardsServer
{
    // 创建质保卡
    public function buildQueueData($brand_id, $batch_id, $num)
    {
        // 获取品牌数据
        $brandInfo = BrandModel::find($brand_id);
        if ($brandInfo) {
            $getTypeInfo = BrandModel::ENVELOPE_TYPE[$brandInfo->envelope_type];

            for ($i = 1; $i <= $num; $i++) {
                // 开启自动补位，最大支持6位
                $currentNum = sprintf("%06d", $i);

                // 设置红包金额
                $money = $brandInfo->envelope_money;
                if ($getTypeInfo['need_random'] === true) {
                    $money = random_int($brandInfo->start_money, $brandInfo->end_money);
                }

                // 投递任务，队列分发
//                CardCreateJob::dispatch($batch_id, $currentNum, $money);
                dispatch(new CardCreateJob($batch_id, $currentNum, $money));
            }
        }
    }

    // 创建质保卡
    public function createCards($batch_id, $currentNum, $money)
    {
        // 构建质保卡要保存的数据
        $saveData = [
            'batch_id' => $batch_id,
            'current_batch_num' => $currentNum,
            'envelope_money' => $money,
        ];

        // 直接进行数据保存
        file_put_contents('save.log', json_encode($saveData, JSON_UNESCAPED_UNICODE) . "\r\n");
    }
}
